//
//  ArticleDetailViewController.swift
//  weile
//
//  Created by LKM on 16/10/16.
//  Copyright © 2016年 LKM. All rights reserved.
//

import UIKit

class ArticleDetailViewController: BaseViewController {
    
    //    NSString *path = [[NSBundle mainBundle] bundlePath];
    //    NSURL *baseURL = [NSURL fileURLWithPath:path];
    //    NSString * htmlPath = [[NSBundle mainBundle] pathForResource:@"index1"
    //    ofType:@"html"];
    //    NSString * htmlCont = [NSString stringWithContentsOfFile:htmlPath
    //    encoding:NSUTF8StringEncoding
    //    error:nil];
    //    [self.webView loadHTMLString:htmlCont baseURL:baseURL];
    var data:ArticleDetailTo?
    var articleId:String!;
    var webView :UIWebView!;
    override func viewDidLoad() {
        super.viewDidLoad()
        isNavigationBarOpacitas=true;
        
         webView = UIWebView()
        webView.frame = view.bounds
        /// 自动对页面进行缩放以适应屏幕
        webView.scalesPageToFit = true
        webView.dataDetectorTypes = .all
        webView.backgroundColor = UIColor.clear
        webView.isOpaque = false;
        
        webView.dataDetectorTypes = UIDataDetectorTypes.link//.remove(UIDataDetectorTypes.link);
        //        LKMLog("=====\(Bundle.main.path(forResource: "html/productDetail", ofType: "html")!)")
        //        let url = URL(string:Bundle.main.path(forResource: "html/productDetail", ofType: "html")! )
        //        let request = URLRequest(url: url!)
        //        webView.loadRequest(request)
        
        
        webView.delegate = self
        view.addSubview(webView)
        
        self.navigationItem.rightBarButtonItems = [
            UIBarButtonItem(image: UIImage(named: "ic_share_archive_666"), style: .plain, target: self, action: #selector(loadShareContent)),
            UIBarButtonItem(image: UIImage(named: "ic_like_archive_666"), style: .plain, target: self, action: #selector(likeUpdata))
            
        ]
        
        self.navigationItem.rightBarButtonItems?[0].tintColor=R.colors._535353;
        self.navigationItem.rightBarButtonItems?[1].tintColor=R.colors._535353;
        
//        LKMLog("==articleId== \(articleId!)")
        
        loadData()
        
    }
    
    func loadData(){
        ViewHelp.showProgressActivity(containView: self.view)
        let ts=Api.getArticleDetail(preTaskSerialNumber: nil, aid: self.articleId) { (re:ResponEntity) in
            
            if(re.isSuccess()){
                
                DispatchQueue.global(qos: .background).async(execute: {
                    
                    let data=re.getData() as! ArticleDetailTo;
                    self.data=data;
                    var xx="";
                    do {
                        
                        //只能base64  不然转义问题
                        let htmlCont=try? String(contentsOfFile: Bundle.main.path(forResource: "html/article/ArticleDetail", ofType: "html")!, encoding:String.Encoding.utf8)
                        let css=try? String(contentsOfFile: Bundle.main.path(forResource: "html/article/ArticleCss", ofType: "css")!, encoding:String.Encoding.utf8)
                        
                        xx = StringHelp.replaceAll(htmlCont, old: "#title#", new: data.Title ?? "");
                        
                        xx = StringHelp.replaceAll(xx, old: "#author#", new: data.Author ?? "");
                        
                        xx = StringHelp.replaceAll(xx, old: "#info#", new: "");
                        
                        xx = StringHelp.replaceAll(xx, old: "#time#", new: data.AddTime ?? "");
                        
                        xx = StringHelp.replaceAll(xx, old: "#content#", new: data.Content ?? "");
                        
                        xx  = xx.replacingOccurrences(of: "#css_include#", with: css!,  options: String.CompareOptions.literal, range: nil)
                        
                        var include=try? String(contentsOfFile: Bundle.main.path(forResource: "html/js/zepto.1.1.6.min", ofType: "js")!, encoding:String.Encoding.utf8)
                        xx = StringHelp.replaceAll(xx, old: "//#js_include_zepto3#", new: include!)


                        include=try? String(contentsOfFile: Bundle.main.path(forResource: "html/js/lazyload.min", ofType: "js")!, encoding:String.Encoding.utf8)
                        xx = StringHelp.replaceAll(xx, old: "//#js_include_lazy4#", new: include!)
                        
                    } catch {
                        // deal with error
                    }
                    
                    DispatchQueue.main.async(execute: {
                        self.webView.loadHTMLString(xx, baseURL:URL(string: Api.getArticleBaseUrl()))
                        
                    })
                    
                })
                
                
                
                
            }else{
                ViewHelp.showTipsView(containView: self.view, tips: "加载失败")
            }
            ViewHelp.hideProgressActivity(containView: self.view)
            
        }
        taskAlls.append(ts)
    }
    
    func bindata_like(){
        
        if self.data == nil{
            return;
        }
        
        self.navigationItem.rightBarButtonItems?[1].tintColor = (self.data?.iskeep ?? 0 ) == 0 ? R.colors._535353 : R.colors.base_color;
    }
    
    var isLikeUpdataIng=false;
    func likeUpdata(){
        if self.data == nil{
            return
        }
        if isLikeUpdataIng {
            return
        }
        isLikeUpdataIng=true;
        
        ViewHelp.showProgressActivity(containView: self.view)
        let ts=Api.CollectArticle(preTaskSerialNumber: nil,id:articleId) { (re:ResponEntity) in
            self.isLikeUpdataIng=false;
            ViewHelp.hideProgressActivity(containView: self.view);
            //            self.contentScrollView.endRefreshing(at: self.refresher.position);
            ViewHelp.showTipsView(containView: self.view, tips: re.msg)
            guard re.isSuccess() else{
                return;
            }
            var data = re.getData() as? [String : Any]  ?? [String : Any]();
            
            
            self.data?.iskeep = (0 == ( (data["Status"] as? Int)  ?? 1 ) ) ? 1 : 0;
            self.bindata_like();
            
        }
        taskAlls.append(ts);
    }
    
    var isLoadShareContent=false;
    func loadShareContent(){
        if(isLoadShareContent){
            return
        }
        isLoadShareContent=true;
        ViewHelp.showProgressActivity(containView: self.view)
        let ts = Api.getArticleShare(preTaskSerialNumber: nil, id:articleId) { (re:ResponEntity) in
            self.isLoadShareContent=false
            ViewHelp.hideProgressActivity(containView: self.view);
            guard re.isSuccess() else{
                ViewHelp.showTipsView(containView: self.view, tips: re.msg)//成功不显示
                return;
            }
            
            let o = re.getData() as! ProductShareTo

            ActivityRequest.showShardDialogViewController(self,title: o.title,content: o.content,url: o.shareurl,imageUrl: StringHelp.isEmpty(self.data?.ImgUrl ) ? "" : Api.getImageUrl(self.data?.ImgUrl ?? ""),localImage: #imageLiteral(resourceName: "ic_logo"));
//            ShareHelp.share(vc: self, text: o.content ?? "", image: "", url: o.shareurl ?? "", finsh: { (isSuccess:Bool) in
//                ViewHelp.showTipsView(containView: self.view, tips: isSuccess ? "分享成功" : "分享失败")
//            })
            
        }
        
        taskAlls.append(ts)
    }
    
    var taskAlls = [Int]();
    deinit {
        //界面退出肯定就不登陆咯
        Api.destroyTask(taskSerialNumbers: taskAlls);
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}
extension ArticleDetailViewController: UIWebViewDelegate {
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        UIApplication.shared.isNetworkActivityIndicatorVisible = true
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        //        SVProgressHUD.dismiss()
        //这会等到图片全部加载完 里面的资源加载完
        UIApplication.shared.isNetworkActivityIndicatorVisible = false
    }
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        return true;
    }
}
